﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

//퍼포스 테스트

public class CharacterInfoScene : Scene
{
    static bool isNeedInitWithItemRoot = false; // 아이템 셀렉트 창으로 바로 갈때
    static MemberModel InitMember = null;

    static public void InitWithItemRoot()
    {
        isNeedInitWithItemRoot = true;
    }

    static public void ModelForInitWithItemRoot(MemberModel model)
    {
        InitMember = model;
    }

    enum SCENEMODE
    {
        info,
        powerUp,
        item,
        preView,
    }

    public MemberModel m_SelectMember = null;
    MemberModel m_PowerUpMaterialMember = null;

    SCENEMODE m_SceneMode = SCENEMODE.info;

    public GameObject m_PowerupPanel;       //강화 관련 패널
    public GameObject m_InfoScrollPanel;


    #region Left List 관련 변수
    int m_MembersMax = 0;
    List<int> m_MembersNo = new List<int>();

    public Animation m_LeftListAni;
    public GameObject m_LeftListOrizin;
    const float ListMemberStartY = 135.0f;
    const float ListMemberGap = 195.0f;
    [HideInInspector]
    public List<Oc_MemberListItem> m_LeftListItems = new List<Oc_MemberListItem>();
    #endregion

    #region 애니메이션 변수
    public GameObject m_InfoUIRoot;           //인포 패널 등장 퇴장 애니
    public Animation m_WeaponAni;           //장착무기 알파 애니
    public Animation m_SortAni;
    public Animation m_PowerUpAni;          //강화 메뉴 등장애니
    public Animation m_CharacterAni;        //캐릭터 중앙 오가는 애니
    public Animation m_InfoTextAni;          //길드원 정보 텍스트 등장애니
    public Animation m_PowerUpTextAni;        //강화 정보 텍스트 등장애니
    public Animation m_ItemTextAni;          //아이템 텍스트 등장애니
    public Animation m_ItemViewUpTextAni;        //미리보기 텍스트 등장애니

    public Animation m_ItemPanelAni;
    public Animation m_PreviewPanelAni;
    public Animation m_InfoPanelAni;
    #endregion

    #region 길드원 강화 관련변수
    public UILabel m_PowerUp_Info_Label01;
    public UILabel m_PowerUp_Info_Label02;
    public UILabel m_PowerUp_Success_Label;
    public UILabel m_PowerUp_Kina_Label;
    public Animation m_PowerUp_Button_Ani;
    public Animation m_PowerUpGagePanelChange;

    public GameObject m_PowerCenter01;
    public GameObject m_PowerCenter02;

    public UISprite m_GreenGage_01;
    public UISprite m_GreenGage_02;
    public UISprite m_RedGage_02;
    public GameObject m_GreenEffect;
    public GameObject m_RedEffect;
    public GameObject m_PowerUpIngEffect;
    public GameObject m_PowerUpSuccessEffect;

    public GameObject m_EnhanceMaterialNothingPanel;


    int m_ParticleStartPosx = -225;
    int m_ParticleEndPosx = 388;
    int m_GageStartDimensionsX = 40;

    bool m_IsPowerUp_Ing = false;

    #endregion

    #region 길드원 정렬 관련 변수

    public UILabel[] m_SortKindsLabel;

    bool m_IsSortMenuOn = false;
    bool IsSortMenuOn
    {
        get { return m_IsSortMenuOn; }
        set
        {
            m_IsSortMenuOn = value;
            MemberListScrollOnOff();
        }
    }

    SortKind m_SortKind = SortKind.Level;

    bool m_IsDescending = true;

    string tempString0 = null;
    string tempString1 = null;
    string tempString2 = null;
    #endregion

    #region 아이템 관련 변수
    public OC_ItemPanelController m_ItemPanelController;
    public Transform m_WeaponRoot;
    public GameObject m_MemberListRoot;

    public GameObject m_PowerUpSuccessRoot;
    public GameObject m_PowerUpFailRoot;

    #endregion



    #region leftlist 무빙 관련
    public UIScrollView m_LeftScrollView;
    const float LeftListScrollViewStartPositonY = -128.0f;
    const float LeftListScrollViewStartOffSetY = -300.0f;
    public bool m_IsLeftListMoving = false;

    public Animation m_LeftBottomAni;

    void UpdateLeftScrollView()
    {
        if (m_IsLeftListMoving)
        {
            SpringPanel sp = m_LeftScrollView.GetComponent("SpringPanel") as SpringPanel;
            if (sp != null)
                sp.enabled = false;

            UIPanel up = m_LeftScrollView.panel;
            Vector2 offSet = up.clipOffset;
            offSet.y = LeftListScrollViewStartOffSetY - m_LeftScrollView.transform.localPosition.y + LeftListScrollViewStartPositonY;
            up.clipOffset = offSet;
        }
    }
    #endregion


    public GameObject m_TraitIncEffect;

    public Transform m_LightProbeAnchorRoot;


    #region 메뉴 컨트롤 부분
    void SetSortMenuUI(int num)        // 소트 메뉴 라벨 설정
    {
        m_SortKind = (SortKind)(((int)m_SortKind + num) % 3);   // 각 상황마다 대응

        switch (m_SortKind)
        {
            case SortKind.Level:
                m_SortKindsLabel[0].text = tempString0;
                m_SortKindsLabel[1].text = tempString1;
                m_SortKindsLabel[2].text = tempString2;
                break;
            case SortKind.Rare:
                m_SortKindsLabel[0].text = tempString1;
                m_SortKindsLabel[1].text = tempString2;
                m_SortKindsLabel[2].text = tempString0;
                break;
            case SortKind.Inhance:
                m_SortKindsLabel[0].text = tempString2;
                m_SortKindsLabel[1].text = tempString0;
                m_SortKindsLabel[2].text = tempString1;
                break;
        }

        SortMember();
        SetLeftListUI();

        if (m_SelectMember == null)
        {
            m_SelectMember = m_LeftListItems[0].m_MemberModel;
        }

        for (int i = 0; i < m_LeftListItems.Count; i++)
        {
            if (m_SelectMember.no == m_LeftListItems[i].m_MemberModel.no)
                m_LeftListItems[i].SetOn(false);
            else
                m_LeftListItems[i].SetOff();
        }
    }

    public void RefreshLeftListAndInfo()
    {
        SetSortMenuUI(m_SortKind);
    }

    void SetSortMenuUI(SortKind kind)        // 소트 메뉴 라벨 설정
    {
        m_SortKind = kind;   // 각 상황마다 대응

        switch (m_SortKind)
        {
            case SortKind.Level:
                m_SortKindsLabel[0].text = tempString0;
                m_SortKindsLabel[1].text = tempString1;
                m_SortKindsLabel[2].text = tempString2;
                break;
            case SortKind.Rare:
                m_SortKindsLabel[0].text = tempString1;
                m_SortKindsLabel[1].text = tempString2;
                m_SortKindsLabel[2].text = tempString0;
                break;
            case SortKind.Inhance:
                m_SortKindsLabel[0].text = tempString2;
                m_SortKindsLabel[1].text = tempString0;
                m_SortKindsLabel[2].text = tempString1;
                break;
        }

        SortMember();
        SetLeftListUI();

        for (int i = 0; i < m_LeftListItems.Count; i++)
        {
            m_LeftListItems[i].SetOff();
        }

        if (m_SceneMode == SCENEMODE.info)
        {
            if (m_SelectMember == null)
                m_SelectMember = m_LeftListItems[0].m_MemberModel;

            UpdateInfoUI(m_SelectMember);

            for (int i = 0; i < m_LeftListItems.Count; i++)
            {
                if (m_LeftListItems[i].m_MemberModel.no == m_SelectMember.no)
                    m_LeftListItems[i].SetOn(false);
            }
        }
        else if (m_SceneMode == SCENEMODE.powerUp)      //여기 수정
        {
            if (m_MembersNo.Count > 0)
            {
                m_PowerUpMaterialMember = m_LeftListItems[0].m_MemberModel;
                UpdatePowerUpUI(m_LeftListItems[0].m_MemberModel);
                m_LeftListItems[0].SetOn(false);
                m_EnhanceMaterialNothingPanel.SetActive(false);
            }
            else
            {
                m_EnhanceMaterialNothingPanel.SetActive(true);
            }
        }
    }

    void SortMember()
    {
        m_MembersNo.Clear();

        List<MemberModel> tList = new List<MemberModel>();

        if (m_SceneMode == SCENEMODE.info)
        {
            foreach (KeyValuePair<string, MemberModel> t in UserData.Instance.userModel.members_dic)
            {
                tList.Add(t.Value);
            }
        }
        else if (m_SceneMode == SCENEMODE.powerUp)
        {
            Debug.Log(m_SelectMember.no);
            Debug.Log(TextController.GetMemberModelDefine(m_SelectMember));
            foreach (KeyValuePair<string, MemberModel> t in UserData.Instance.userModel.members_dic)
            {
                if (m_SelectMember.no == t.Value.no)
                    continue;

                bool isChoiceMember = false;
                foreach (int no in UserData.Instance.userModel.choiceMembers)
                {
                    if (no == t.Value.no)
                    {
                        isChoiceMember = true;
                        break;
                    }
                }

                if (!isChoiceMember)
                    tList.Add(t.Value);
            }
        }

        int max = tList.Count;
        for (int i = 0; i < max - 1; i++)
        {
            for (int j = 0; j < max - 1; j++)
            {
                switch (m_SortKind)
                {
                    case SortKind.Level:
                        {
                            if (tList[j].level < tList[j + 1].level)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case SortKind.Rare:
                        {
                            if (tList[j].rarity < tList[j + 1].rarity)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                    case SortKind.Inhance:
                        {
                            if (tList[j].strengthening < tList[j + 1].strengthening)
                            {
                                MemberModel t = tList[j];
                                tList[j] = tList[j + 1];
                                tList[j + 1] = t;
                            }
                        }
                        break;
                }
            }
        }

        for (int i = 0; i < max; i++)
        {
            if (m_IsDescending)
                m_MembersNo.Add(tList[i].no);
            else
                m_MembersNo.Add(tList[max - i - 1].no);
        }
    }

    void MemberListScrollOnOff()
    {
        foreach(Oc_MemberListItem item in m_LeftListItems)
        {
            UIDragScrollView sv = item.GetComp("UIDragScrollView") as UIDragScrollView;
            sv.enabled = !IsSortMenuOn;
        }
    }

    void OnLoginErrCallback(ResponseModel<UserModel> recvData)
    {
        Debug.LogError("OnLoginErrCallback");
    }

    void OnLoginCallback(ResponseModel<UserModel> userData)
    {
        UserData.Instance.userModel = userData.data;
        StartCoroutine("StartSceneWithDelay");
    }

    public override void AwakeScene()
    {
        Instance = this;

        //left리스트 드래그 스크롤뷰 설정
        UIDragScrollView tDs = m_LeftListOrizin.GetComponent("UIDragScrollView") as UIDragScrollView;
        tDs.scrollView = m_LeftScrollView;

        Popup_Blur.ClearAll();


        // test version code  /////////////////////////////////////////////
        /**/
        if (UserData.Instance.userModel == null)
        {
            LoadingScene.TestInit();
            /**/
            //NetworkManager.Instance.C2S_LOGIN(AuthPlatformID.None, "hshshs", "asd", OnLoginCallback, OnLoginErrCallback);
            NetworkManager.Instance.C2S_GSTAR_JOIN(OnLoginCallback, OnLoginErrCallback);
        }
        /////////////////////////////////////////////////////////////////
        else
        {
            StartCoroutine("StartSceneWithDelay");
        }
    }

    IEnumerator StartSceneWithDelay()
    {
        yield return new WaitForSeconds(0.0f);

        tempString0 = TextController.GetStringWithId("uiCommonTextLevel");
        tempString1 = TextController.GetStringWithId("uiCommonTextRarityDo");
        tempString2 = TextController.GetStringWithId("uiCommonTextEnhance");

        //일단 레벨순으로 설정
        m_SortKindsLabel[0].text = tempString0;
        m_SortKindsLabel[1].text = tempString1;
        m_SortKindsLabel[2].text = tempString2;

        m_MembersMax = UserData.Instance.userModel.members_dic.Count;

        SortMember();

        CreateList();

        StartSceneAni();
    }

    void CreateList()
    {
        // 정렬메뉴 x -700 에서 씬 시작
        Vector3 pos = m_SortAni.transform.localPosition;
        pos.x = -700.0f;
        m_SortAni.transform.localPosition = pos;

        SortMember();

        // 레프트 메뉴 x -700 에서 씬 시작
        GameObject temp = null;
        Oc_MemberListItem tempML = null;
        for (int i = 0; i < m_MembersMax; i++)
        {
            if (i > 0)
                temp = Instantiate(m_LeftListOrizin) as GameObject;
            else
                temp = m_LeftListOrizin;

            temp.transform.parent = m_LeftListOrizin.transform.parent;
            temp.transform.localScale = m_LeftListOrizin.transform.localScale;
            temp.name = string.Format("memberList_A{0}", i + 1);
            tempML = temp.GetComponent("Oc_MemberListItem") as Oc_MemberListItem;
            tempML.SetList(UserData.Instance.userModel.members_dic[m_MembersNo[i].ToString()]);
            m_LeftListItems.Add(tempML);
        }


        if (m_SelectMember == null)
            m_SelectMember = m_LeftListItems[0].m_MemberModel;
        UpdateInfoUI(m_SelectMember);

        for (int i = 0; i < m_LeftListItems.Count; i++)
        {
            if (m_LeftListItems[i].m_MemberModel.no == m_SelectMember.no)
                m_LeftListItems[i].SetOn(false);
        }
    }

    void SetLeftListPos()
    {
        Vector3 pos = Vector3.zero;
        float OnListGap = 0.0f;
        for (int i = 0; i < m_MembersMax; i++)
        {
            pos = m_LeftListItems[i].transform.localPosition;
            pos.y = ListMemberStartY - (ListMemberGap * i) - OnListGap;
            m_LeftListItems[i].transform.localPosition = pos;

            if (m_SelectMember != null)
            {
                if (m_LeftListItems[i].m_MemberModel.no == m_SelectMember.no)
                    OnListGap = 20.0f;
            }
        }
    }

    void SetLeftListUI()
    {
        for (int i = 0; i < m_MembersMax; i++)
        {
            if (i < m_MembersNo.Count)
            {
                m_LeftListItems[i].gameObject.SetActive(true);
                m_LeftListItems[i].SetList(UserData.Instance.userModel.members_dic[m_MembersNo[i].ToString()]);
            }
            else
                m_LeftListItems[i].gameObject.SetActive(false);
        }
    }

    public override void StartScene()
    {
        //StartSceneAni();

        //Localization.language = "text_ko";
    }


    void InfoUIAni(bool isUp, float delay)
    {
        float time = 1.0f;
        if (isUp)
        {
            iTween.MoveTo(m_InfoUIRoot, iTween.Hash("islocal", true, "delay", delay, "time", time, "y", -123.0f, "oncompletetarget", gameObject, "oncomplete", "OnFInishedInfoUIAnimation"));
        }
        else
        {
            iTween.MoveTo(m_InfoUIRoot, iTween.Hash("islocal", true, "delay", delay, "time", time, "y", -1500.0f));
        }
    }

    public void OnFInishedInfoUIAnimation()
    {
        if (UserData.Instance.userModel.questInfo.state == 3)
        {
            GameObject obj = Resources.Load("Prefab/UI/touch") as GameObject;
            GameObject questMarker = Instantiate(obj) as GameObject;
            QuestManager.instance.touchIndicatorList.Add(questMarker);

            DQuestInfo questInfo = GameData.Inst.GetQuestInfo(UserData.Instance.userModel.questInfo.questId);

            switch (questInfo.objective)
            {
                case 1:
                    questMarker.transform.parent = m_InfoUIRoot.transform;
                    questMarker.transform.localPosition = new Vector3(442f, 445f, 0f);
                    questMarker.transform.localScale = Vector3.one;
                    break;
                case 2:
                    questMarker.transform.parent = m_InfoUIRoot.transform;
                    questMarker.transform.localPosition = new Vector3(0f, -520f, 0f);
                    questMarker.transform.localScale = Vector3.one;
                    break;
                case 11:
                    questMarker.transform.parent = m_InfoUIRoot.transform;
                    questMarker.transform.localPosition = new Vector3(-320f, -520f, 0f);
                    questMarker.transform.localScale = Vector3.one;
                    break;
                case 21:
                    questMarker.transform.parent = m_InfoUIRoot.transform;
                    questMarker.transform.localPosition = new Vector3(1060f, -450f, 0f);
                    questMarker.transform.localScale = Vector3.one;
                    break;
            }
        }

    }

    public void StartSceneAni()
    {
        //Popup_Tutorial pt = PopupManager.PushPopup(PopupKind.Tutorial) as Popup_Tutorial;
        //pt.SetPopupWithTutorialKind(TutorialKind.helpCharChangeInfo);


        if (isNeedInitWithItemRoot)
        {
            //infoList 패널 밑으로
            Vector3 pos = m_InfoUIRoot.transform.localPosition;   //인포 패널 시작 y -1500으로 시작
            pos.y = -1500.0f;
            m_InfoUIRoot.transform.localPosition = pos;

            m_SelectMember = InitMember;

            m_WeaponAni.Play("info_weapon_Aoff");
            GoItemMenu();

            isNeedInitWithItemRoot = false;
            InitMember = null;

            SetCharacterModel(m_SelectMember);
        }
        else
        {
            SetActiveHelpButton(false);

            //infoList 패널 올라오는 애니
            Vector3 pos = m_InfoUIRoot.transform.localPosition;   //인포 패널 시작 y -1500으로 시작
            pos.y = -1500.0f;
            m_InfoUIRoot.transform.localPosition = pos;
            InfoUIAni(true, 0.5f);

            MemberListAni(true);

            m_WeaponAni.Play("info_weapon_Aon");
            m_InfoTextAni.Play("3D_Text_in");
            m_InfoTextAni.Play("3D_Text_idle", AnimationPlayMode.Queue);
            m_PowerUpTextAni.Play("3D_Text_out");
        }
    }


    public void EndSceneAni()
    {
        m_LeftListAni.Play("info_detail_list OUT");
        InfoUIAni(false, 0);
    }


    void UpdatePowerUpUI(MemberModel tempModel)
    {
        m_PowerUp_Info_Label01.text = string.Format(TextController.GetStringWithId("uiCharUpgradeCaution1"), TextController.GetStringWithId(string.Format("charName{0}", tempModel.name)));
        m_PowerUp_Info_Label02.text = TextController.GetStringWithId("uiCharUpgradeOngoing");
        m_PowerUp_Kina_Label.text = "150";

        float probablility = m_SelectMember.CalcStrengthenProbability(tempModel);
        //최대 651
        m_GreenGage_01.SetDimensions((int)(probablility * 651.0f), 38);

        int percentage = (int)(probablility * 100.0f);

        StartCoroutine("SetPowerUp_Success_LabelText", string.Format("{0} [7eff00]+{1}%[-]", TextController.GetStringWithId("uiCharUpgradeSuccessRate"), percentage));
    }

    IEnumerator SetPowerUp_Success_LabelText(string msg)
    {
        yield return new WaitForSeconds(0.0f);
        m_PowerUp_Success_Label.text = msg;
    }

    void UpdateInfoUI(MemberModel tempModel)
    {
        //membermodel
        SetCharacterModel(tempModel);

        OC_InfoUIWithScroll.instance.UpdateInfoUI(tempModel);

        // 아이템 있는지 없는지 판단해서 웨폰 아이콘 유무 판별
        Transform leftRight = m_WeaponRoot.Find("LeftItem");
        Oc_ItemShowBox sb = leftRight.GetComponent("Oc_ItemShowBox") as Oc_ItemShowBox;
        sb.SetItem(tempModel.leftItem, true);
        leftRight = m_WeaponRoot.Find("RightItem");
        sb = leftRight.GetComponent("Oc_ItemShowBox") as Oc_ItemShowBox;
        sb.SetItem(tempModel.rightItem, false);

        //리스트 포지션 이동
        SetLeftListPos();
    }


    public override void ButtonTouch(Collider collider)  // 버튼 터치 (터치 시작 끝 같은 오브젝트일때 터치 끝 시점에 호출)
    {
        Debug.Log(collider.name);

        if (collider.name.Contains("memberList_A"))
        {
            Oc_MemberListItem Choise_ML = collider.GetComponent("Oc_MemberListItem") as Oc_MemberListItem;

            if (m_SceneMode == SCENEMODE.info)
            {
                if (m_SelectMember.no != Choise_ML.m_MemberModel.no)      // 이전 선택 길드원과 다를때
                {
                    m_SelectMember = Choise_ML.m_MemberModel;
                    UpdateInfoUI(m_SelectMember);
                    // 다른 인원 선택시 인포 리스트 초기화 
                    OC_InfoUIWithScroll.instance.m_SelectListNum = -1;
                    OC_InfoUIWithScroll.instance.MoveList();
                }
            }
            else if (m_SceneMode == SCENEMODE.powerUp)
            {
                UpdatePowerUpUI(Choise_ML.m_MemberModel);
                m_PowerUpMaterialMember = Choise_ML.m_MemberModel;
            }
            else if (m_SceneMode == SCENEMODE.item)
            {
                m_SelectMember = Choise_ML.m_MemberModel;
                UpdateInfoUI(m_SelectMember);
                m_ItemPanelController.UpdateUI(false);
                m_ItemPanelController.RefreshMemberListOut();
            }

            foreach (Oc_MemberListItem t_ML in m_LeftListItems)
            {
                if (t_ML.Equals(Choise_ML))
                    t_ML.SetOn(true);
                else
                    t_ML.SetOff();
            }
        }
        else if (collider.name.Contains("Button_Sort_"))
        {
            if (IsSortMenuOn)
            {
                string buttonName = collider.gameObject.name.Replace("Button_Sort_", "");
                int num = System.Convert.ToInt32(buttonName);
                SetSortMenuUI(num);
                m_SortAni.Play("sort_close");
            }
            else
            {
                m_SortAni.Play("sort_open");
            }
            IsSortMenuOn = !IsSortMenuOn;
        }
        else
        {
            switch (collider.gameObject.name)
            {
                case "Button_Init":
                    {
                        //Popup_TwoButton popupSc = PopupManager.PushPopup(PopupKind.TwoButton) as Popup_TwoButton;
                        //popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCharInfoDismiss"), string.Format(TextController.GetStringWithId("uiPopupCharInfoDismiss"),
                        //    TextController.GetStringWithId(string.Format("charName{0}", m_SelectMember.name))));
                        //popupSc.SetPopupWithYesNoString(TextController.GetStringWithId("uiCharInfoDismiss"), TextController.GetStringWithId("uiCommonTextNo"));
                        //popupSc.SetEventOK(gameObject, "OnDismissPopup");

                        NetworkManager.Instance.C2S_MEMBER_InitTrait(m_SelectMember.no, OnInitTraitCallback);
                    }
                    break;

                case "Button_Equip":
                    {
                        GoItemMenu();
                    }
                    break;

                case "Button_GoPowerUp":           // 강화 버튼
                    {
                        GoPowerUpMenu();
                    }
                    break;
                case "Button_Detail":
                    {
                        Popup_Info_detail popupSc = PopupManager.PushPopup(PopupKind.Info_detail) as Popup_Info_detail;
                        popupSc.SetPopupWithMember(m_SelectMember);
                    }
                    break;
                case "Button_Dismiss":
                    {
                        if (UserData.Instance.userModel.regions.isDispatchingMember(m_SelectMember.no))
                        {
                            Popup_OneButton popupSc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
                            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId("uiCommonTextDispatchCaution1"));
                        }
                        else
                        {
                            Popup_TwoButton popupSc = PopupManager.PushPopup(PopupKind.TwoButton) as Popup_TwoButton;
                            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCharInfoDismiss"), string.Format(TextController.GetStringWithId("uiPopupCharInfoDismiss"),
                                TextController.GetStringWithId(string.Format("charName{0}", m_SelectMember.name))));
                            popupSc.SetPopupWithYesNoString(TextController.GetStringWithId("uiCharInfoDismiss"), TextController.GetStringWithId("uiCommonTextNo"));
                            popupSc.SetEventOK(gameObject, "OnDismissPopup");
                        }
                    }
                    break;
                case "Button_Visual":
                    {
                        GoItemPreViewMenu();
                    }
                    break;
                case "Button_GoItem":
                    {
                        GoItemMenu();
                    }
                    break;
                case "Button_updown":
                    m_IsDescending = !m_IsDescending;
                    
                    collider.transform.Find("Up").gameObject.SetActive(!m_IsDescending);
                    collider.transform.Find("Down").gameObject.SetActive(m_IsDescending);     
                    
                    SetSortMenuUI(m_SortKind);
                    break;

                case "Button_Sort":
                    {
                        if (IsSortMenuOn)
                            m_SortAni.Play("sort_close");
                        else
                        {
                            //for (int i = 0; i < SortingNum; i++)
                            //{
                            //    m_SortKindsLabel[i].text = m_SortKindsLabel[i];
                            //}

                            m_SortAni.Play("sort_open");
                        }

                        IsSortMenuOn = !IsSortMenuOn;
                    }
                    break;

                case "Button_PowerUp":
                    {
                        // 강화 할건지 묻는 팝업 출력
                        Popup_SpendKina popupSc = PopupManager.PushPopup(PopupKind.SpendKina) as Popup_SpendKina;
                        popupSc.SetPopupWithMaterialName(TextController.GetStringWithId(string.Format("charName{0}", m_PowerUpMaterialMember.name)));

                        popupSc.SetEventOK(gameObject, "On_PowerUpOK");
                    }
                    break;

                case "Button_Trait":
                    {
                        string buttonNo = collider.transform.parent.parent.name.Replace("infoList0", "");
                        int buttonNumber = int.Parse(buttonNo) - 1;

                        NetworkManager.Instance.C2S_MEMBER_IncTrait(m_SelectMember.no, m_SelectMember.traits[buttonNumber], 1,
                            OnIncTraitCallback);
                    }
                    break;
                case "Button_Infopopup":
                    PopupManager.PushPopup(PopupKind.Character_Info);
                    Debug.Log("Button_Infopopup");
                    break;

                case "Button_Back":
                    BackButton();
                    break;
            }
        }
    }

    void OnIncTraitCallback(ResponseModel<MemberModel> data)
    {
        // 특성 포인트 완료
        if (data.ecode == 0)
        {
            // 인포 리프리쉬
            // 데이터 치환후
            MemberModel member = data.data;
           
            foreach (KeyValuePair<string, MemberModel> t in UserData.Instance.userModel.members_dic)
            {
                if (t.Value.no == member.no)
                {
                    t.Value.DataCopy(member);
                    m_SelectMember = t.Value;
                    break;
                }
            }

            OC_InfoUIWithScroll.instance.StatTextAniPlay();

            UserData.Instance.userModel.SetChoiceMembersList();

            m_TraitIncEffect.SetActive(false);
            m_TraitIncEffect.SetActive(true);

            SoundController.PlaySound("UI_Character_Up");

            UpdateInfoUI(m_SelectMember);

            if (data.responseResult.completeIdList.Count != 0)
            {
                foreach (int id in data.responseResult.completeIdList)
                {
                    ToastManager.Instance.ShowAchievementCompleteToast(id, true);
                }
            }

            Invoke("GetQuestInfo", 0.5f);
            //NetworkManager.Instance.C2S_GET_QUESTINFO(QuestManager.instance.ResponseGetQuestInfo);
        }
        else if (data.ecode == -3111) // 특성 증가 실패
        {
            Popup_TwoButton popupSc = PopupManager.PushPopup(PopupKind.TwoButton) as Popup_TwoButton;

            string errorId = string.Format("systemErrorText{0}", Math.Abs(data.ecode));

            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(errorId));
            popupSc.SetPopupWithYesNoString(TextController.GetStringWithId("uiCharUpgradeTitle"), TextController.GetStringWithId("uiCommonTextNo"));
            popupSc.SetEventOK(gameObject, "OnTraitInc3111");
        }
        else
        {
            Popup_OneButton popupSc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;

            string errorId = string.Format("systemErrorText{0}", Math.Abs(data.ecode));

            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(errorId));
        }
    }

    void OnInitTraitCallback(ResponseModel<MemberModel> data) //
    {
        // 특성 포인트 초기화 완료
        if (data.ecode == 0)
        {
            // 인포 리프리쉬
            // 데이터 치환후
            MemberModel member = data.data;
            string key = null;
            foreach (KeyValuePair<string, MemberModel> t in UserData.Instance.userModel.members_dic)
            {
                if (t.Value.no == member.no)
                {
                    t.Value.DataCopy(member);
                    m_SelectMember = t.Value;
                    break;
                }
            }

            UserData.Instance.userModel.SetChoiceMembersList();

            UpdateInfoUI(m_SelectMember);

            if (data.responseResult.completeIdList.Count != 0)
            {
                foreach (int id in data.responseResult.completeIdList)
                {
                    ToastManager.Instance.ShowAchievementCompleteToast(id, true);
                }
            }

            Invoke("GetQuestInfo", 0.5f);
            //NetworkManager.Instance.C2S_GET_QUESTINFO(QuestManager.instance.ResponseGetQuestInfo);
        }
        else
        {
            Popup_OneButton popupSc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;

            string errorId = string.Format("systemErrorText{0}", Math.Abs(data.ecode));

            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(errorId));
        }
    }

    void OnTraitInc3111()
    {
        GoPowerUpMenu();
    }

    void OnDismissPopup() // 해고 팝업 오케이 버튼 핸들러
    {
        NetworkManager.Instance.C2S_MEMBER_Disch(m_SelectMember.no, OnDischCallback);
    }

    void On_PowerUpOK()     // 팝업 콜백
    {
        if (UserData.Instance.userModel.kina > Constants.EnhanceKina)
        {
            if (UserData.Instance.userModel.regions.isDispatchingMember(m_PowerUpMaterialMember.no))
            {
                Popup_OneButton popupSc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
                popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId("uiCommonTextDispatchCaution2"));
            }
            else
            {
                NetworkManager.Instance.C2S_MEMBER_STRENG(m_SelectMember.no, m_PowerUpMaterialMember.no, OnMEMBER_STRENGCallback);
                m_PowerUp_Button_Ani.Play("PowerUp_Button_FadeOut");
            }
        }
        else
        {
            Popup_OneButton popupSc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;
            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId("systemErrorText2004"));
        }
    }

    void OnDischCallback(ResponseModel<UserModel> data) // 해고 네트워크 콜백
    {
        if (data.ecode == 0)
        {
            UserData.Instance.userModel = data.data;
            m_SelectMember = null;
            // 데이터 치환후
            SetSortMenuUI(m_SortKind);
            MemberListAni(true);

            if (data.responseResult.completeIdList.Count != 0)
            {
                foreach (int id in data.responseResult.completeIdList)
                {
                    ToastManager.Instance.ShowAchievementCompleteToast(id, true);
                }
            }

            Invoke("GetQuestInfo", 0.5f);
            //NetworkManager.Instance.C2S_GET_QUESTINFO(QuestManager.instance.ResponseGetQuestInfo);
        }
        else
        {
            Popup_OneButton popupSc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;

            string errorId = string.Format("systemErrorText{0}", Math.Abs(data.ecode));

            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(errorId));
        }
    }

    void GoPowerUpMenu()
    {
        IgnoreTouch();

        SetModelRotateButton(true);

        SoundController.PlaySound("UI_screen_slide");

        SetActiveHelpButton(false);

        m_SceneMode = SCENEMODE.powerUp;

        SetGageInit();
        MemberListAni(true);


        InfoUIAni(false, 0);
        m_WeaponAni.Play("info_weapon_Aoff");
        m_CharacterAni.CrossFade("char_moveToPower");
        m_InfoTextAni.Play("3D_Text_out");
        m_PowerUpTextAni.Play("3D_Text_in");
        m_PowerUpTextAni.Play("3D_Text_idle", AnimationPlayMode.Queue);

        if (IsSortMenuOn)
            m_SortAni.Play("sort_close");

        SetSortMenuUI(m_SortKind);

        if (m_MembersNo.Count > 0)
        {
            m_PowerUpAni.Play("powerUP_up");
            m_PowerUp_Button_Ani.Play("PowerUp_Button_FadeIN");
        }
    }

    void IgnoreTouch()
    {
        IsAbleControl = false;
        StopCoroutine("UnignoreTouch");
        StartCoroutine("UnignoreTouch");
    }

    IEnumerator UnignoreTouch()
    {
        yield return new WaitForSeconds(0.5f);
        IsAbleControl = true;
    }

    void GoInfoMenu()
    {
        IgnoreTouch();

        SetModelRotateButton(true);

        SoundController.PlaySound("UI_screen_slide");

        SetActiveHelpButton(false);

        SCENEMODE PreSceneMode = m_SceneMode;
        m_SceneMode = SCENEMODE.info;

        // 멤버리스트 인포로 이동
        m_MemberListRoot.transform.parent = GameObject.Find("infoPanel").transform.Find("Root");
        // 드래그 이벤트 취소
        foreach (Oc_MemberListItem t in m_LeftListItems)
        {
            t.m_EventRecieaver = null;
        }


        MemberListAni(true);

        if (PreSceneMode == SCENEMODE.powerUp)
            m_PowerUpAni.Play("powerUP_down");

        m_PowerUp_Button_Ani.Play("PowerUp_Button_FadeOut");
        InfoUIAni(true, 0);
        m_WeaponAni.Play("info_weapon_Aon");
        m_InfoTextAni.Play("3D_Text_in");
        m_InfoTextAni.Play("3D_Text_idle", AnimationPlayMode.Queue);

        if (PreSceneMode == SCENEMODE.item)
        {
            m_InfoPanelAni.Play("RootAlpha_In");
            m_ItemPanelAni.Play("RootAlpha_Out");
            m_CharacterAni.CrossFade("char_backToInfo");
            m_ItemTextAni.Play("3D_Text_out");
        }
        else
        {
            m_CharacterAni.CrossFade("char_moveToInfo");
            m_PowerUpTextAni.Play("3D_Text_out");
        }


        SetSortMenuUI(m_SortKind);

        // 강화 메테리얼 없을때 뜨는 패널 혹시나 있을까봐...
        m_EnhanceMaterialNothingPanel.SetActive(false);
    }

    void EndLeftListMove()
    {
        m_IsLeftListMoving = false;
    }

    void LeftListCollidersOn()
    {
        for (int i = 0; i < m_LeftListItems.Count; i++)
        {
            m_LeftListItems[i].collider.enabled = true;
        }
    }

    public void MemberListAni(bool isIn)
    {
        if (isIn)
        {
            //들어오는 애니는 무조건 스크롤 부분 초기화 해서 들어옴
            Vector3 pos = m_LeftScrollView.transform.localPosition;
            pos.y = LeftListScrollViewStartPositonY;
            m_LeftScrollView.transform.localPosition = pos;

            UIPanel up = m_LeftScrollView.panel;
            Vector2 offSet = up.clipOffset;
            offSet.y = LeftListScrollViewStartOffSetY - m_LeftScrollView.transform.localPosition.y + LeftListScrollViewStartPositonY;
            up.clipOffset = offSet;


            LeftListCollidersOn();

            // Vector3 pos = m_SortAni.transform.localPosition;
            pos = m_SortAni.transform.localPosition;
            pos.x = -700.0f;
            m_SortAni.transform.localPosition = pos;

            iTween.MoveTo(m_SortAni.gameObject, iTween.Hash("islocal", true, "x", -3.0f, "time", 0.5f, "easetype", "spring"));

            int maxAni = System.Math.Min(m_LeftListItems.Count, 6);     // 한번에 보여줄수있는 최대 리스트 갯수 6개 이하 예외 처리
            for (int i = 0; i < maxAni; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = -700.0f;
                m_LeftListItems[i].transform.localPosition = pos;

                iTween.MoveTo(m_LeftListItems[i].gameObject, iTween.Hash("islocal", true, "x", 1.0f, "time", 0.5f, "easetype", "spring", "delay", (i * 0.1f)));
            }

            for (int i = maxAni; i < m_LeftListItems.Count; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = 1.0f;
                m_LeftListItems[i].transform.localPosition = pos;
            }
        }
        else
        {
            m_IsLeftListMoving = true;      // 나가는 에니만 리스트 올림

            iTween.MoveTo(m_LeftScrollView.gameObject, iTween.Hash("islocal", true, "y", LeftListScrollViewStartPositonY, "time", 0.2f, "easetype", "spring",
                "oncompletetarget", gameObject, "oncomplete", "EndLeftListMove"));

            for (int i = 0; i < m_LeftListItems.Count; i++)  // 아웃 무빙시 콜라이더 디스에이블
            {
                m_LeftListItems[i].collider.enabled = false;
            }

            Vector3 pos = m_SortAni.transform.localPosition;
            pos.x = -3.0f;
            m_SortAni.transform.localPosition = pos;

            iTween.MoveTo(m_SortAni.gameObject, iTween.Hash("islocal", true, "x", -700.0f, "time", 0.5f, "easetype", "spring"));      // 나가는 애니

            int maxAni = System.Math.Min(m_LeftListItems.Count, 6);     // 한번에 보여줄수있는 최대 리스트 갯수 6개 이하 예외 처리
            for (int i = 0; i < maxAni; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = 1.0f;
                m_LeftListItems[i].transform.localPosition = pos;

                if (i == maxAni - 1)  // 마지막 놈에 엔드 함수 호출
                    iTween.MoveTo(m_LeftListItems[i].gameObject, iTween.Hash("islocal", true, "x", -700.0f, "time", 0.5f, "easetype", "spring", "delay", (i * 0.1f))); // 나가는 애니                
                else
                    iTween.MoveTo(m_LeftListItems[i].gameObject, iTween.Hash("islocal", true, "x", -700.0f, "time", 0.5f, "easetype", "spring", "delay", (i * 0.1f))); // 나가는 애니
            }

            for (int i = maxAni; i < m_LeftListItems.Count; i++)
            {
                pos = m_LeftListItems[i].transform.localPosition;
                pos.x = -700.0f;
                m_LeftListItems[i].transform.localPosition = pos;
            }
        }
    }


    void GoItemMenu()
    {
        IgnoreTouch();

        SetModelRotateButton(false);

        SoundController.PlaySound("UI_screen_slide");

        SetActiveHelpButton(false);

        SCENEMODE PreSceneMode = m_SceneMode;
        m_SceneMode = SCENEMODE.item;

        m_ItemPanelController.UpdateUI(true);

        m_ItemTextAni.Play("3D_Text_in");
        m_ItemTextAni.Play("3D_Text_idle", AnimationPlayMode.Queue);

        m_LeftBottomAni.Play("CharacterInfo_Item_LeftBottom_Alpha_in");

        if (PreSceneMode == SCENEMODE.info)
        {
            m_CharacterAni.CrossFade("char_moveToItem");
            m_InfoPanelAni.Play("RootAlpha_Out");
            m_ItemPanelAni.Play("RootAlpha_In");

            m_InfoTextAni.Play("3D_Text_out");
        }
        else
        {
            m_CharacterAni.CrossFade("char_backToItem");
            m_PreviewPanelAni.Play("RootAlpha_Out");
            m_ItemPanelAni.Play("RootAlpha_In");

            m_ItemViewUpTextAni.Play("3D_Text_out");
        }

        Invoke("ShowQuestTouchIndicator", 0.4f);
    }

    void ShowQuestTouchIndicator()
    {
        if (UserData.Instance.userModel.questInfo.state == 3)
        {
            GameObject obj = Resources.Load("Prefab/UI/touch") as GameObject;
            GameObject questMarker = Instantiate(obj) as GameObject;
            QuestManager.instance.touchIndicatorList.Add(questMarker);
            GameObject questMarker2 = Instantiate(obj) as GameObject;
            QuestManager.instance.touchIndicatorList.Add(questMarker2);

            DQuestInfo questInfo = GameData.Inst.GetQuestInfo(UserData.Instance.userModel.questInfo.questId);

            switch (questInfo.objective)
            {
                case 21:
                    questMarker.transform.parent = m_ItemPanelController.transform;
                    questMarker.transform.localPosition = new Vector3(-1000f, -500f, 0f);
                    questMarker.transform.localScale = Vector3.one;
                    questMarker2.transform.parent = m_ItemPanelController.transform;
                    questMarker2.transform.localPosition = new Vector3(440f, 100f, 0f);
                    questMarker2.transform.localScale = Vector3.one;
                    break;
            }

            if ( !m_ItemPanelController.m_ScrollItemList.IsHaveItem() )
                questMarker2.SetActive(false);
            if (m_SelectMember != null && m_SelectMember.leftItem == null && m_SelectMember.rightItem == null)
                questMarker.SetActive(false);
        }
    }

    void GoItemPreViewMenu()
    {
        IgnoreTouch();

        SetModelRotateButton(false);

        SoundController.PlaySound("UI_screen_slide");

        SetActiveHelpButton(false);

        SCENEMODE PreSceneMode = m_SceneMode;
        m_SceneMode = SCENEMODE.preView;

        m_ItemPanelAni.Play("RootAlpha_Out");
        m_PreviewPanelAni.Play("RootAlpha_In");
        m_CharacterAni.CrossFade("char_moveToView");
    }

    public override void BackButton()
    {
        if (m_SceneMode == SCENEMODE.powerUp)
        {
            if (!m_IsPowerUp_Ing)
                GoInfoMenu();
        }
        else if (m_SceneMode == SCENEMODE.info)
        {
            SceneController.LoadLevel("Main");
        }
        else if (m_SceneMode == SCENEMODE.item)
        {
            GoInfoMenu();
        }
        else if (m_SceneMode == SCENEMODE.preView)
        {
            GoItemMenu();
        }
    }
    #endregion

    void GetQuestInfo()
    {
        NetworkManager.Instance.C2S_GET_QUESTINFO(QuestManager.instance.ResponseGetQuestInfo);
    }


    #region 강화 애니 관련 정의

    bool m_IsGageMoving = false;

    public override void UpdateScene()
    {
        UpdateGage();
        UpdateLeftScrollView();
    }

    void StartGageMove(bool isSuccess)
    {
        m_IsPowerUp_Ing = true;

        MemberListAni(false);

        m_PowerUpGagePanelChange.Play("PowerUpGagePanelChange");

        StartCoroutine(GageMove(isSuccess));
    }

    IEnumerator GageMove(bool isSuccess)
    {
        yield return new WaitForSeconds(1.0f);
       
        m_IsGageMoving = true;
        System.Random rand = new System.Random();

        float aniTime = 4.0f;
        float EndAniTime = 0.2f;
        int max = m_ParticleEndPosx - m_ParticleStartPosx;

        int step = 20;
        //-225   ~  388
        int moveMax = max / (step + 1);
        int moveMin = (int)((float)moveMax * 0.3f);

        Vector3[] pos1 = new Vector3[step];
        Vector3[] pos2 = new Vector3[step];


        float y1 = 35.0f;
        float y2 = -37.0f;
        if (!isSuccess)
        {
            y2 = 35.0f;
            y1 = -37.0f;
        }

        int randNum1 = 0;
        int randNum2 = 0;

        pos1[0].Set(m_ParticleStartPosx, y1, 2.0f);
        pos2[0].Set(m_ParticleStartPosx, y2, 2.0f);

        for (int i = 1; i < step; i++)
        {
            randNum1 = rand.Next(moveMin, moveMax);
            randNum2 = rand.Next(moveMin, moveMax);

            pos1[i].Set(pos1[i - 1].x + (float)randNum1, y1, 2.0f);
            pos2[i].Set(pos2[i - 1].x + (float)randNum2, y2, 2.0f);
        }

        SetGageInit();

        if (isSuccess)
        {
            iTween.MoveTo(m_GreenEffect, iTween.Hash("islocal", true, "movetopath", false, "path", pos1, "time", aniTime - EndAniTime, "easetype", "easeInCubic"));
            iTween.MoveTo(m_RedEffect, iTween.Hash("islocal", true, "movetopath", false, "path", pos2, "time", aniTime - EndAniTime, "easetype", "easeInCubic"));

            iTween.MoveTo(m_GreenEffect, iTween.Hash("islocal", true, "x", max + m_ParticleStartPosx, "time", EndAniTime, "easetype", "easeInCubic",
                "oncompletetarget", gameObject, "oncomplete", "EndGageMoveSuc", "delay", aniTime - EndAniTime));
        }
        else
        {
            iTween.MoveTo(m_GreenEffect, iTween.Hash("islocal", true, "movetopath", false, "path", pos2, "time", aniTime - EndAniTime, "easetype", "easeInCubic"));
            iTween.MoveTo(m_RedEffect, iTween.Hash("islocal", true, "movetopath", false, "path", pos1, "time", aniTime - EndAniTime, "easetype", "easeInCubic"));

            iTween.MoveTo(m_RedEffect, iTween.Hash("islocal", true, "x", max + m_ParticleStartPosx, "time", EndAniTime, "easetype", "easeInCubic",
                "oncompletetarget", gameObject, "oncomplete", "EndGageMoveFail", "delay", aniTime - EndAniTime));
        }

        // 파워업중 케릭터 배경 이펙트 (파티클 동작)
        m_PowerUpIngEffect.SetActive(true);

        SoundController.PlaySound("UI_gathering_cast", true);
    }

    void SetGageInit()      // 게이지 리셋
    {
        iTween.Stop(m_GreenEffect);
        iTween.Stop(m_RedEffect);

        m_GreenEffect.transform.localPosition = new Vector3(m_ParticleStartPosx, 35.0f, 2.0f);
        m_RedEffect.transform.localPosition = new Vector3(m_ParticleStartPosx, -37.0f, 2.0f);

        m_GreenGage_02.SetDimensions(m_GageStartDimensionsX, 29);
        m_RedGage_02.SetDimensions(m_GageStartDimensionsX, 29);

        m_PowerUpIngEffect.SetActive(false);
        m_PowerUpSuccessEffect.SetActive(false);
    }

    void UpdateGage()
    {
        if (m_IsGageMoving)
        {
            m_GreenGage_02.SetDimensions((int)m_GreenEffect.transform.localPosition.x - m_ParticleStartPosx + m_GageStartDimensionsX, 29);
            m_RedGage_02.SetDimensions((int)m_RedEffect.transform.localPosition.x - m_ParticleStartPosx + m_GageStartDimensionsX, 29);
        }
    }

    void EndGageMoveSuc()   // 성공시 이펙트 플레이
    {
        //마지막 이펙트 터치는 곳

        SoundController.StopSound("UI_gathering_cast");
        SoundController.PlaySound("UI_intension_success");

        m_PowerUpSuccessEffect.SetActive(true);

        m_PowerUpSuccessRoot.SetActive(true);

        StartCoroutine(GoInfoMenu(1.0f));
    }

    void EndGageMoveFail()
    {
        SoundController.StopSound("UI_gathering_cast");
        SoundController.PlaySound("UI_intension_fail");

        m_PowerUpFailRoot.SetActive(true);
        //마지막 이펙트 터치는 곳       
        StartCoroutine(GoInfoMenu(1.0f));
    }


    IEnumerator GoInfoMenu(float waitTime)
    {
        Invoke("GetQuestInfo", 0.5f);

        yield return new WaitForSeconds(waitTime);
        m_IsGageMoving = false;
        m_IsPowerUp_Ing = false;
        SetGageInit();
        m_PowerUpSuccessRoot.SetActive(false);
        m_PowerUpFailRoot.SetActive(false);

        m_PowerUpGagePanelChange.Play("PowerUpGagePanelChangeOff");
        GoInfoMenu();
    }

    #endregion

    #region  콜백 함수들

    void OnMEMBER_STRENGCallback(ResponseModel<UserModel> Data)
    {       
        if (Data.ecode == 0)
        {
            UserData.Instance.userModel = Data.data;
            //SetSortMenuUI(m_SortKind);  연출후 인포 메뉴 들어갈때 실행하는 코드 존재

            m_SelectMember = UserData.Instance.userModel.members_dic[m_SelectMember.no.ToString()];
            UpdateInfoUI(m_SelectMember);

            StartGageMove(true);

            if (Data.responseResult.completeIdList.Count != 0)
            {
                foreach (int id in Data.responseResult.completeIdList)
                {
                    ToastManager.Instance.ShowAchievementCompleteToast(id, true);
                }
            }

            //NetworkManager.Instance.C2S_GET_QUESTINFO(QuestManager.instance.ResponseGetQuestInfo);
        }
        else if (Data.ecode == -3114) // 강화 실패
        {
            UserData.Instance.userModel = Data.data;
            //SetSortMenuUI(m_SortKind);  연출후 인포 메뉴 들어갈때 실행하는 코드 존재
            StartGageMove(false);
        }
        else if (Data.ecode == -3112) // 강화 실패
        {
            Popup_TwoButton popupSc = PopupManager.PushPopup(PopupKind.TwoButton) as Popup_TwoButton;

            string errorId = string.Format("systemErrorText{0}", Math.Abs(Data.ecode));

            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(errorId));
            popupSc.SetPopupWithYesNoString(TextController.GetStringWithId("uiMainWorld"), TextController.GetStringWithId("uiCommonTextNo"));
            popupSc.SetEventOK(gameObject, "OnEnhanceFail3112");

            m_PowerUp_Button_Ani.Play("PowerUp_Button_FadeIN");
        }
        else
        {
            Popup_OneButton popupSc = PopupManager.PushPopup(PopupKind.OneButton) as Popup_OneButton;

            string errorId = string.Format("systemErrorText{0}", Math.Abs(Data.ecode));

            popupSc.SetPopupWithTitleAndBody(TextController.GetStringWithId("uiCommonTextwarning"), TextController.GetStringWithId(errorId));


            m_PowerUp_Button_Ani.Play("PowerUp_Button_FadeIN");
        }
    }


    void OnEnhanceFail3112()
    {
        //SceneController.LoadLevel("World");
        SceneController.LoadLevel("World_GStar");
    }


    void OnCancelPowerup()
    {
        m_PowerUp_Button_Ani.Play("PowerUp_Button_FadeIN");
    }

    #endregion


    // 동적 케릭터 모델 관리
    GameObject m_3DPosition = null;
    [HideInInspector]
    public GameObject m_3DModel = null; // 케릭터 루트
    public GameObject m_3DModelRotateButton;

    Vector3 m_OrizinAngle;

    void SetModelRotateButton(bool isOn)
    {
        m_3DModelRotateButton.SetActive(isOn);

        if (isOn)
            iTween.RotateTo(m_3DModel, iTween.Hash("islocal", true, "y", m_OrizinAngle.y, "time", 1.0f));
        else
            m_3DModel.transform.localRotation = Quaternion.Euler(m_OrizinAngle);
    }

    void SetCharacterModel(MemberModel selectModel)
    {
        if (m_3DPosition == null)
            m_3DPosition = GameObject.Find("LobbyVersion/Position");

        string modelName = GameData.Inst.ModelDefineDic[selectModel.model];

        if (m_3DModel != null && m_3DModel.name.Equals(modelName))  // 같은 위치 케릭터면 이전 케릭터 재사용
            return;
        if (m_3DModel != null)
            Destroy(m_3DModel);

		m_3DModel = BattleResManager.CreatePawn(0, selectModel.model, false);

        RuntimeMeshChanger rtmc = m_3DModel.GetComponent("RuntimeMeshChanger") as RuntimeMeshChanger;
        if (rtmc != null)
        {
           // Debug.Log("adfadfadsf");
            rtmc.ChangeToLow();
        }

        //m_3DModel.name = modelName;

        //Transform root = m_3DPosition.transform;
        //int nRemoveIndex = modelName.IndexOf("_", StringComparison.Ordinal);
        //string model_no = modelName;
        //if (nRemoveIndex != -1)
        //    model_no = modelName.Remove(nRemoveIndex);

        //m_OrizinAngle = m_3DModel.transform.localRotation.eulerAngles;

        //for (int j = 0; j < root.childCount; j++)
        //{
        //    int nIndex = root.GetChild(j).name.IndexOf("_", StringComparison.Ordinal);
        //    string rootName = root.GetChild(j).name;
        //    if (nIndex != -1)
        //        rootName = rootName.Remove(nIndex);

        //    if (rootName.Equals(model_no))
        //    {
        //        m_3DModel.transform.parent = root.GetChild(j);
        //        m_3DModel.transform.localScale = Vector3.one;
        //        m_3DModel.transform.localPosition = Vector3.zero;
        //        m_3DModel.transform.localRotation = Quaternion.Euler(Vector3.zero);

        //        m_3DModel.transform.parent.Find("floor").gameObject.SetActive(true);
        //    }
        //    else
        //        root.GetChild(j).Find("floor").gameObject.SetActive(false);
        //}

        m_3DModel.name = modelName;

        Transform root = m_3DPosition.transform;
        int nRemoveIndex = modelName.IndexOf("_", StringComparison.Ordinal);
        string model_no = modelName;
        bool isHaveUnderBar = (nRemoveIndex != -1);

        m_OrizinAngle = m_3DModel.transform.localRotation.eulerAngles;

        for (int j = 0; j < root.childCount; j++)
        {
            bool isCorrectRoot = false;
            if (isHaveUnderBar)
            {
                string rootName = root.GetChild(j).name.Remove(4);
                string childName = model_no.Remove(4);
                isCorrectRoot = rootName.Equals(childName);
            }
            else    // 언더바 안들은 애들은 이전 방식으로 찾는다
            {
                string rootName = root.GetChild(j).name;
                string childName = model_no;
                isCorrectRoot = rootName.Contains(childName);
            }

            if (isCorrectRoot)
            {
                m_3DModel.transform.parent = root.GetChild(j);
                m_3DModel.transform.localScale = Vector3.one;
                m_3DModel.transform.localPosition = Vector3.zero;
                m_3DModel.transform.localRotation = Quaternion.Euler(Vector3.zero);

                m_3DModel.transform.parent.Find("floor").gameObject.SetActive(true);
            }
            else
                root.GetChild(j).Find("floor").gameObject.SetActive(false);
        }

        var ani = m_3DModel.MakeComponent<Animation>();
        ani["lobby01"].clip.wrapMode = WrapMode.Loop;
        ani.Play("lobby01");        

        AttachWeapon(selectModel, m_3DModel);

        AttachAnchor();
    }

    void AttachAnchor()
    {
        SkinnedMeshRenderer[] tList = m_3DModel.GetComponentsInChildren<SkinnedMeshRenderer>();

        if (tList != null)
        {
            Transform tempAnchor = m_LightProbeAnchorRoot.Find(m_3DModel.name);

            for (int i = 0; i < tList.Length; i++)
            {
                tList[i].lightProbeAnchor = tempAnchor;
            }
        }
    }

    public override void HelpButton()
    {
        switch (m_SceneMode)
        {
            case SCENEMODE.info:
                {
                    Popup_Tutorial pt = PopupManager.PushPopup(PopupKind.Tutorial) as Popup_Tutorial;
                    pt.SetPopupWithTutorialKind(TutorialKind.helpCharInfoInfoA);
                    pt.SetEventOK(gameObject, "OnTutorialNext");
                }
                break;
        }
    }

    void OnTutorialNext()
    {
        Popup_Tutorial pt = PopupManager.PushPopup(PopupKind.Tutorial) as Popup_Tutorial;
        pt.SetPopupWithTutorialKind(TutorialKind.helpCharInfoInfoB);
    }


    GameObject[] m_WeaponModels = new GameObject[2];
    BattleCharInfo AttachWeapon(GameObject _parent, Item L_item, Item R_item)
    { 
        for (int i = 0; i < 2; i++)
        {
            if (m_WeaponModels[i] != null)
                DestroyImmediate(m_WeaponModels[i]);
        }

        int[] itemModelId = new int[2];

        if (R_item != null)
        {
            //Debug.Log(R_item.itemInfo);
            itemModelId[0] = R_item.itemInfo.modelID;           
        }


        if (L_item != null)
            itemModelId[1] = L_item.itemInfo.modelID;

        BattleCharInfo charInfo = _parent.GetComponent("BattleCharInfo") as BattleCharInfo;

        m_WeaponModels = BattleResManager.AttachWeapon(_parent, charInfo, itemModelId, true);

        return charInfo;
    }

    public BattleCharInfo AttachWeapon(MemberModel member, GameObject _parent)
    { 
        return AttachWeapon(_parent, member.leftItem, member.rightItem);
    }

    public void ChangeWepon(Item item)
    {      
        if (item == null)    // 장착 중 무기로 변경  
        {
            AttachWeapon(m_SelectMember, m_3DModel);
        }
        else
        {
            if (item.itemInfo.part == 1)
                AttachWeapon(m_3DModel, null, item);
            else if (item.itemInfo.part == 2)
                AttachWeapon(m_3DModel, item, null);
            else
                AttachWeapon(m_3DModel, item, item);
        }
    }
}
